from pymud import PyMudApp, Session, Trigger
from functools import partial
import json
import traceback

PLUGIN_NAME    = "msg_server"

PLUGIN_DESC = {
    "VERSION" : "1.0.0",
    "AUTHOR"  : "spirytus",
    "RELEASE_DATE"  : "2024-03-12",
    "DESCRIPTION" : "通过socket为客户端提供消息服务"
}

SERVER_IP = "127.0.0.1"
PORT = 54481

class PkuMsgService():
    def __init__(self,session:Session) -> None:
        self.session = session
        self.router = {
            "cmd":self._exec_cmd,
            "capture": self._capture
        }
    
    def parse(self, msg:str):
        if not self.session:
            return
        try:
            data = json.loads(msg)
            for key in data:
                if key in self.router:
                    self.router[key](data[key])
        except Exception as e:
            traceback.print_exc()
        
    def _exec_cmd(self,cmd):
        self.session.exec_command(cmd)
    
    def _capture(self,capture):
        self.session.pku_plug_data["capture"] = capture
        
        

def PLUGIN_PYMUD_START(app: PyMudApp):
    app.set_status(f"插件{PLUGIN_NAME}已加载!")
    pass

def PLUGIN_SESSION_CREATE(session: Session):
    from pkulib.broker import MudBroker

    if not hasattr(session,"pku_service"):
        session.pku_service = {}
    
    if not hasattr(session, "pku_plug_data"):
        session.pku_plug_data = {}

    pku_msg = PkuMsgService(session)
    session.pku_service["msg"] = MudBroker(SERVER_IP,PORT,session)
    session.pku_service["msg"].run(pku_msg.parse)
    pass

def PLUGIN_SESSION_DESTROY(session: Session):
    session.pku_service["msg"].stop()
    pass